/**
 * FloatingView 组件演示
 * 
 * 演示场景：
 * 1. 基础悬浮按钮 - 简单的圆形悬浮按钮（支持点击和长按）
 * 2. 视频通话窗口 - 模拟音视频通话最小化窗口
 * 3. 自动贴边悬浮 - 拖动后自动贴到屏幕边缘
 * 4. 悬浮工具栏 - 带多个按钮的悬浮工具栏
 * 5. 禁用拖动 - 固定位置的悬浮提示
 */

import React, {useState} from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
} from 'react-native';
import {FloatingView} from './components/FloatingView';
import { SafeAreaView } from 'react-native-safe-area-context';

// ==================== 类型定义 ====================

type DemoType =
  | 'basicButton'
  | 'videoCall'
  | 'autoSnap'
  | 'toolbar'
  | 'fixed'
  | null;

interface VideoCallState {
  isMuted: boolean;
  isVideoOn: boolean;
  duration: string;
}

// ==================== 主组件 ====================

export const TestFloatingView: React.FC = () => {
  // ==================== 状态管理 ====================

  const [activeDemo, setActiveDemo] = useState<DemoType>(null);
  const [floatingMessage, setFloatingMessage] = useState('');
  const [videoCallState, setVideoCallState] = useState<VideoCallState>({
    isMuted: false,
    isVideoOn: true,
    duration: '05:24',
  });

  // ==================== 事件处理 ====================

  const openDemo = (type: DemoType) => {
    setActiveDemo(type);
    setFloatingMessage('');
  };

  const closeDemo = () => {
    setActiveDemo(null);
    setFloatingMessage('');
  };

  const handleFloatingPress = (message: string) => {
    setFloatingMessage(message);
  };

  const handleDragEnd = (x: number, y: number) => {
    console.log('悬浮组件拖动结束:', {x, y});
  };

  const toggleMute = () => {
    setVideoCallState(prev => ({...prev, isMuted: !prev.isMuted}));
  };

  const toggleVideo = () => {
    setVideoCallState(prev => ({...prev, isVideoOn: !prev.isVideoOn}));
  };

  // ==================== 渲染函数 ====================

  // 渲染按钮
  const renderButton = (
    title: string,
    type: DemoType,
    description: string,
  ) => (
    <TouchableOpacity
      style={styles.demoButton}
      onPress={() => openDemo(type)}
      activeOpacity={0.7}
    >
      <View style={styles.buttonContent}>
        <Text style={styles.buttonTitle}>{title}</Text>
        <Text style={styles.buttonDescription}>{description}</Text>
      </View>
      <Text style={styles.buttonArrow}>→</Text>
    </TouchableOpacity>
  );

  // ==================== 主渲染 ====================

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContent}>
        {/* 标题 */}
        <View style={styles.header}>
          <Text style={styles.title}>🎈 悬浮组件</Text>
          <Text style={styles.subtitle}>
            可拖动的悬浮视图，支持边界检查和自定义内容
          </Text>
        </View>

        {/* 消息显示 */}
        {floatingMessage ? (
          <View style={styles.messageContainer}>
            <Text style={styles.messageText}>{floatingMessage}</Text>
          </View>
        ) : null}

        {/* 演示按钮列表 */}
        <View style={styles.demoSection}>
          <Text style={styles.sectionTitle}>📱 演示场景</Text>

          {renderButton(
            '1️⃣ 基础悬浮按钮',
            'basicButton',
            '简单的圆形悬浮按钮，支持点击、长按和拖动',
          )}

          {renderButton(
            '2️⃣ 视频通话窗口',
            'videoCall',
            '模拟音视频通话最小化窗口，带控制按钮',
          )}

          {renderButton(
            '3️⃣ 自动贴边悬浮',
            'autoSnap',
            '拖动后自动贴到最近的屏幕边缘',
          )}

          {renderButton(
            '4️⃣ 悬浮工具栏',
            'toolbar',
            '带多个按钮的水平工具栏',
          )}

          {renderButton(
            '5️⃣ 固定位置',
            'fixed',
            '禁用拖动，固定在指定位置',
          )}
        </View>

        {/* 技术说明 */}
        <View style={styles.infoSection}>
          <Text style={styles.infoTitle}>✨ 技术特性</Text>
          <Text style={styles.infoText}>• 悬浮在应用内容之上</Text>
          <Text style={styles.infoText}>• 支持拖动移动位置</Text>
          <Text style={styles.infoText}>• 自动边界检查，防止移出屏幕</Text>
          <Text style={styles.infoText}>• 支持自定义子组件</Text>
          <Text style={styles.infoText}>• 可配置初始位置</Text>
          <Text style={styles.infoText}>• 支持点击、长按和拖动事件</Text>
          <Text style={styles.infoText}>• 智能手势识别（区分点击、长按、拖动）</Text>
          <Text style={styles.infoText}>• 完整的 TypeScript 类型支持</Text>
        </View>

        {/* 应用外悬浮窗说明 */}
        <View style={styles.warningSection}>
          <Text style={styles.warningTitle}>⚠️ 应用外悬浮窗说明</Text>
          <Text style={styles.warningText}>
            <Text style={styles.bold}>Android:</Text> 需要申请
            SYSTEM_ALERT_WINDOW 权限，使用 WindowManager 实现系统级悬浮窗。
          </Text>
          <Text style={styles.warningText}>
            <Text style={styles.bold}>iOS:</Text>{' '}
            限制严格，不支持真正的系统级悬浮窗，只能在应用内实现或使用 PiP
            模式。
          </Text>
          <Text style={styles.warningText}>
            本组件实现的是<Text style={styles.bold}>应用内悬浮</Text>
            ，适用于大多数场景，无需额外权限。
          </Text>
        </View>

        {/* 关闭按钮 */}
        {activeDemo && (
          <TouchableOpacity style={styles.closeButton} onPress={closeDemo}>
            <Text style={styles.closeButtonText}>关闭悬浮组件</Text>
          </TouchableOpacity>
        )}
      </ScrollView>

      {/* ==================== 悬浮组件演示 ==================== */}

      {/* 1. 基础悬浮按钮 */}
      {activeDemo === 'basicButton' && (
        <FloatingView
          onPress={() => handleFloatingPress('点击了基础悬浮按钮！')}
          onLongPress={() => handleFloatingPress('长按了基础悬浮按钮！可以显示菜单等操作')}
          onDragEnd={handleDragEnd}
        >
          <View style={styles.basicFloatingButton}>
            <Text style={styles.floatingButtonText}>➕</Text>
          </View>
        </FloatingView>
      )}

      {/* 2. 视频通话窗口 */}
      {activeDemo === 'videoCall' && (
        <FloatingView
          style={styles.videoCallContainer}
          onPress={() => handleFloatingPress('点击视频通话窗口')}
          onDragEnd={handleDragEnd}
        >
          <View style={styles.videoCallWindow}>
            {/* 视频预览区域 */}
            <View style={styles.videoPreview}>
              <View style={styles.avatarPlaceholder}>
                <Text style={styles.avatarText}>👤</Text>
              </View>
              <Text style={styles.callerName}>张三</Text>
              <Text style={styles.callDuration}>{videoCallState.duration}</Text>
            </View>

            {/* 控制按钮 */}
            <View style={styles.videoControls}>
              <TouchableOpacity
                style={[
                  styles.controlButton,
                  videoCallState.isMuted && styles.controlButtonActive,
                ]}
                onPress={toggleMute}
              >
                <Text style={styles.controlButtonText}>
                  {videoCallState.isMuted ? '🔇' : '🔊'}
                </Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[
                  styles.controlButton,
                  !videoCallState.isVideoOn && styles.controlButtonActive,
                ]}
                onPress={toggleVideo}
              >
                <Text style={styles.controlButtonText}>
                  {videoCallState.isVideoOn ? '📹' : '📷'}
                </Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.controlButton, styles.endCallButton]}
                onPress={closeDemo}
              >
                <Text style={styles.controlButtonText}>📞</Text>
              </TouchableOpacity>
            </View>
          </View>
        </FloatingView>
      )}

      {/* 3. 自动贴边悬浮 */}
      {activeDemo === 'autoSnap' && (
        <FloatingView
          autoSnapToEdge={true}
          onPress={() => handleFloatingPress('点击了自动贴边按钮')}
          onDragEnd={handleDragEnd}
        >
          <View style={styles.snapFloatingButton}>
            <Text style={styles.floatingButtonText}>↔️</Text>
            <Text style={styles.snapButtonLabel}>拖我</Text>
          </View>
        </FloatingView>
      )}

      {/* 4. 悬浮工具栏 */}
      {activeDemo === 'toolbar' && (
        <FloatingView
          style={styles.toolbarContainer}
          initialY={100}
          onDragEnd={handleDragEnd}
        >
          <View style={styles.floatingToolbar}>
            <TouchableOpacity
              style={styles.toolbarButton}
              onPress={() => handleFloatingPress('点击了首页')}
            >
              <Text style={styles.toolbarButtonText}>🏠</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.toolbarButton}
              onPress={() => handleFloatingPress('点击了搜索')}
            >
              <Text style={styles.toolbarButtonText}>🔍</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.toolbarButton}
              onPress={() => handleFloatingPress('点击了消息')}
            >
              <Text style={styles.toolbarButtonText}>💬</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={styles.toolbarButton}
              onPress={() => handleFloatingPress('点击了设置')}
            >
              <Text style={styles.toolbarButtonText}>⚙️</Text>
            </TouchableOpacity>
          </View>
        </FloatingView>
      )}

      {/* 5. 固定位置悬浮 */}
      {activeDemo === 'fixed' && (
        <FloatingView
          draggable={false}
          initialX={20}
          initialY={150}
          onPress={() => handleFloatingPress('这是一个固定位置的提示')}
        >
          <View style={styles.fixedFloating}>
            <Text style={styles.fixedFloatingText}>💡</Text>
            <Text style={styles.fixedFloatingLabel}>提示</Text>
          </View>
        </FloatingView>
      )}
    </SafeAreaView>
  );
};

// ==================== 样式定义 ====================

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F7FA',
  },
  scrollContent: {
    padding: 20,
    paddingBottom: 100,
  },
  header: {
    marginBottom: 24,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#1A1A1A',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    color: '#666666',
    lineHeight: 22,
  },
  messageContainer: {
    backgroundColor: '#E8F5E9',
    padding: 16,
    borderRadius: 12,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: '#4CAF50',
  },
  messageText: {
    fontSize: 16,
    color: '#2E7D32',
    fontWeight: '600',
  },
  demoSection: {
    marginBottom: 24,
  },
  sectionTitle: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#1A1A1A',
    marginBottom: 16,
  },
  demoButton: {
    backgroundColor: '#FFFFFF',
    padding: 16,
    borderRadius: 12,
    marginBottom: 12,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    // iOS 阴影
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    // Android 阴影
    elevation: 2,
  },
  buttonContent: {
    flex: 1,
  },
  buttonTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#1A1A1A',
    marginBottom: 4,
  },
  buttonDescription: {
    fontSize: 14,
    color: '#666666',
    lineHeight: 20,
  },
  buttonArrow: {
    fontSize: 24,
    color: '#007AFF',
    marginLeft: 12,
  },
  infoSection: {
    backgroundColor: '#E3F2FD',
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#2196F3',
    marginBottom: 16,
  },
  infoTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#1565C0',
    marginBottom: 12,
  },
  infoText: {
    fontSize: 14,
    color: '#1976D2',
    lineHeight: 24,
  },
  warningSection: {
    backgroundColor: '#FFF3E0',
    padding: 16,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#FF9800',
    marginBottom: 16,
  },
  warningTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#E65100',
    marginBottom: 12,
  },
  warningText: {
    fontSize: 14,
    color: '#EF6C00',
    lineHeight: 22,
    marginBottom: 8,
  },
  bold: {
    fontWeight: 'bold',
  },
  closeButton: {
    backgroundColor: '#F44336',
    padding: 16,
    borderRadius: 12,
    alignItems: 'center',
    marginTop: 8,
  },
  closeButtonText: {
    fontSize: 16,
    fontWeight: '600',
    color: '#FFFFFF',
  },

  // ==================== 悬浮组件样式 ====================

  // 基础悬浮按钮
  basicFloatingButton: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: '#007AFF',
    justifyContent: 'center',
    alignItems: 'center',
  },
  floatingButtonText: {
    fontSize: 28,
    color: '#FFFFFF',
  },

  // 自动贴边按钮
  snapFloatingButton: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: '#4CAF50',
    justifyContent: 'center',
    alignItems: 'center',
  },
  snapButtonLabel: {
    fontSize: 10,
    color: '#FFFFFF',
    marginTop: 2,
  },

  // 视频通话窗口
  videoCallContainer: {
    // 不需要默认的圆角阴影
    shadowOpacity: 0.4,
    shadowRadius: 12,
  },
  videoCallWindow: {
    width: 140,
    backgroundColor: '#1E1E1E',
    borderRadius: 16,
    overflow: 'hidden',
  },
  videoPreview: {
    height: 180,
    backgroundColor: '#2C2C2C',
    justifyContent: 'center',
    alignItems: 'center',
  },
  avatarPlaceholder: {
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: '#444444',
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 8,
  },
  avatarText: {
    fontSize: 32,
  },
  callerName: {
    fontSize: 14,
    fontWeight: '600',
    color: '#FFFFFF',
    marginBottom: 4,
  },
  callDuration: {
    fontSize: 12,
    color: '#AAAAAA',
  },
  videoControls: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    paddingVertical: 12,
    paddingHorizontal: 8,
    backgroundColor: '#1E1E1E',
  },
  controlButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    backgroundColor: '#3C3C3C',
    justifyContent: 'center',
    alignItems: 'center',
  },
  controlButtonActive: {
    backgroundColor: '#007AFF',
  },
  endCallButton: {
    backgroundColor: '#F44336',
  },
  controlButtonText: {
    fontSize: 16,
  },

  // 悬浮工具栏
  toolbarContainer: {
    shadowOpacity: 0.3,
  },
  floatingToolbar: {
    flexDirection: 'row',
    backgroundColor: '#FFFFFF',
    borderRadius: 25,
    paddingHorizontal: 8,
    paddingVertical: 8,
  },
  toolbarButton: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: '#F5F5F5',
    justifyContent: 'center',
    alignItems: 'center',
    marginHorizontal: 4,
  },
  toolbarButtonText: {
    fontSize: 20,
  },

  // 固定位置悬浮
  fixedFloating: {
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: '#FF9800',
    justifyContent: 'center',
    alignItems: 'center',
  },
  fixedFloatingText: {
    fontSize: 24,
  },
  fixedFloatingLabel: {
    fontSize: 10,
    color: '#FFFFFF',
    fontWeight: '600',
    marginTop: 2,
  },
});

